import { asyncRouterMap, constantRouterMap } from '../../router'
import _ from 'lodash'
import * as types from '../mutation-types'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission (permissions, route) {

  /**
   * 如果定义了 permission的话，需要验证，否则，直接放行
   */
  if (route.meta && route.meta.permission) {

    return permissions.indexOf(route.meta.permission) !== -1

  } else {

    return true

  }

}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter (asyncRouterMap, permissions) {

  const accessedRouters = asyncRouterMap.filter(route => {

    if (hasPermission(permissions, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, permissions)
      }
      return true
    }
    return false
  });


  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    menuRoutes: []
  },
  getters: {
    addRouters: state => state.addRouters,
    menuRoutes: state => state.menuRoutes,
    routers: state => state.routers
  },
  mutations: {
    [types.SET_ROUTERS] (state, routers) {

      state.addRouters = _.cloneDeep(routers)

      state.routers = _.cloneDeep(constantRouterMap.concat(routers))

    },
    [types.SET_MENU_ROUTES] (state, routers) {

      state.menuRoutes = routers

    }
  },
  actions: {
    GenerateRoutes ({ commit }, data) {
      return new Promise(resolve => {
        const permissons = data.permissions
        let accessedRouters
        accessedRouters = filterAsyncRouter(asyncRouterMap, permissons)
        commit(types.SET_ROUTERS, accessedRouters)
        resolve()
      })
    },
    GenerateMenuRoutes ({commit, state}, data) {
      const topNav = data.topNav || asyncRouterMap[0].name
      const permissons = data.permissions
      let accessedRouters
      accessedRouters = _.find(_.cloneDeep(constantRouterMap.concat(state.addRouters)), obj => {
        return obj.name === topNav
      }).children
      accessedRouters = filterAsyncRouter(accessedRouters, permissons)
      commit(types.SET_MENU_ROUTES, accessedRouters)
    }
  }
}

export default permission
